package com.ufgov.ip.service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import com.ufgov.ip.base.service.IPDataTableService;
import com.ufgov.ip.dao.IuapUserDao;
import com.ufgov.ip.dao.IuapUserJdbcDao;
import com.ufgov.ip.dao.impl.IuapUserJdbcDaoImpl;
import com.ufgov.ip.entity.IpUser;
import com.ufgov.ip.entity.IpUserCompany;
import com.ufgov.ip.sysmanager.dao.ICompanyDao;
import com.ufgov.ip.sysmanager.dao.IPRoleDao;
import com.ufgov.ip.sysmanager.dao.IpUserCompanyDao;
import com.ufgov.ip.sysmanager.dao.IpUserRoleDao;
import com.ufgov.ip.sysmanager.entity.IpCompany;
import com.ufgov.ip.sysmanager.entity.IpRole;
import com.ufgov.ip.sysmanager.entity.IpUserRole;
import com.ufgov.ip.util.CopyPropertiesUtil;
import com.ufgov.ip.util.UUIDTools;

/**
 * 用户管理服务层
 * 书写readonly是说明没有特殊标识服务层只有只读事物
 * @author guangsa
 *
 */
@Component
@Transactional(readOnly=true)
public class UserAccountService {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	private static Logger logger = LoggerFactory.getLogger(UserAccountService.class);

	@Autowired
	private IuapUserDao userDao;
	
	@Autowired
	private IPRoleDao iPRoleDao;
	
	@Autowired
	private ICompanyDao coDao;
	
	@Autowired
	private IpUserCompanyDao ipUserCompanyDao;
	
	@Autowired
	private IpUserRoleDao ipUserRoleDao;
	
	
	@Autowired
    private IuapUserJdbcDaoImpl iuapUserJdbcDao;
	
	
	@Autowired
	private IPDataTableService ipDataTableService;
	
	
	/*@Autowired
	private IuapHirerDao hirerDao;*/
	
	
	
	/*public void setHirerDao(IuapHirerDao hirerDao) {
		this.hirerDao = hirerDao;
	}*/

	public IpUserCompanyDao getIpUserCompanyDao() {
		return ipUserCompanyDao;
	}


	public IpUserRoleDao getIpUserRoleDao() {
		return ipUserRoleDao;
	}


	public IPRoleDao getiPRoleDao() {
		return iPRoleDao;
	}


	public void setiPRoleDao(IPRoleDao iPRoleDao) {
		this.iPRoleDao = iPRoleDao;
	}


	public ICompanyDao getCoDao() {
		return coDao;
	}


	public void setCoDao(ICompanyDao coDao) {
		this.coDao = coDao;
	}


	public IuapUserDao getUserDao() {
		return userDao;
	}


	public void setUserDao(IuapUserDao userDao) {
		this.userDao = userDao;
	}

	/**
	 * 根据用户名称得到相应的用户信息
	 * @param loginName
	 * @return
	 */
	public IpUser findUserByLoginName(String loginName) {
		return userDao.findByLoginName(loginName);
	}

	
	/**
	 * 根据用户手机得到相应的用户信息
	 * @param loginName
	 * @return
	 */
	public IpUser findUserByCellphoneNo(String cellphoneNo) {
		return userDao.findUserByCellphoneNo(cellphoneNo);
	}
	
	/**
	 * 根据用户邮箱得到相应的用户信息
	 * @param loginName
	 * @return
	 */
	public IpUser findUserByUserEmail(String userEmail) {
		return userDao.findUserByUserEmail(userEmail);
	}
	public IpUser findUserByUserEmailOrLoginNameOrCellphoneNo(String logicName) {
		return userDao.findUserByUserEmailOrLoginNameOrCellphoneNo(logicName);
	}

	@SuppressWarnings("unchecked")
	@Transactional
	public void saveIpUserEntity(IpUser ipUserEntity,
			IpCompany ic, IpRole ir,List list,Map<String, String> resultMap) {

		        IpUser ipUser=checkIpUser(ipUserEntity,resultMap);
		        IpUser selUser=new IpUser();
				if(ipUser==null){
					ipUserEntity.setUserId(UUIDTools.uuidRandom());
					CopyPropertiesUtil.setProperty(ipUserEntity);
					selUser=ipUserEntity;
					userDao.save(ipUserEntity);
				}else{
					CopyPropertiesUtil.copyProperty(ipUser, ipUserEntity);
					selUser=ipUser;
					userDao.save(ipUser);
				}
					//添加_部门
					IpUserCompany setProperties = setCoProperties(ic,selUser);
					//添加_职务
					IpUserRole setRoleProperties = setRoleProperties(ir,setProperties.getCoId(), selUser, "0");
					
					//保存职务、部门关联信息
					IpUserCompany checkIpUserCompany = checkIpUserCompany(setProperties,resultMap);
					if(checkIpUserCompany==null){
						ipUserCompanyDao.save(setProperties);
					}else{
						setProperties.setTheId(checkIpUserCompany.getTheId());
						CopyPropertiesUtil.copyProperty(checkIpUserCompany, setProperties);
						ipUserCompanyDao.save(checkIpUserCompany);
					}
					
					IpUserRole checkIpUserRole = checkIpUserRole(setRoleProperties,resultMap);
					if(checkIpUserRole==null){
						//setProperties.setCoId(checkIpUserCompany.getCoId());
						ipUserRoleDao.save(setRoleProperties);
					}else{
						setRoleProperties.setTheId(checkIpUserRole.getTheId());
						CopyPropertiesUtil.copyProperty(checkIpUserRole, setRoleProperties);
						ipUserRoleDao.save(setRoleProperties);
					}
					
					
					
					//添加兼职
					if(list.size()!=0){
					//添加_兼职部门
					List<IpUserRole> ipUserRoleList = (List<IpUserRole>) list.get(0);
					List<IpUserCompany> ipUserCompanyList = (List<IpUserCompany>) list.get(1);
					int show_p_coId=0;
					//在保存兼职的时候删除原来的兼职
					ipUserRoleDao.deleteUserRoleByUserIdAndIsPartTime(selUser.getUserId(),"1");
					//添加_兼职的职务
					for (IpUserRole ipUserRole : ipUserRoleList) {//添加的都是最新的
						ipUserRole.setUserId(selUser.getUserId());
							String roleId = ipUserRole.getRoleId();
							IpRole findByRoleId = iPRoleDao.findByRoleId(roleId);
							setRoleProperties(findByRoleId,ipUserCompanyList.get(show_p_coId).getCoId(), selUser, ipUserRole.getIsPartTime());
							ipUserRoleDao.save(ipUserRole);
						    show_p_coId++;
					}
				}
	}
	
	
	
	public IpUserCompany setCoProperties(IpCompany ic,IpUser ipUserEntity){
		IpUserCompany userCo=new IpUserCompany();
		String coId = ic.getCoId();
		IpCompany findByCoId = coDao.findByCoId(coId);
		userCo.setCoCode(findByCoId.getCoCode());
		userCo.setCoId(findByCoId.getCoId());
		userCo.setCoName(findByCoId.getCoFullname());
		userCo.setTheId(UUIDTools.uuidRandom());
		userCo.setUserId(ipUserEntity.getUserId());
		return userCo;
		
	}
	public IpUserRole setRoleProperties(IpRole ir,String coId, IpUser ipUserEntity,String flag){
		IpUserRole userRole=new IpUserRole();
		String roleId = ir.getRoleId();
		if(roleId==null){
			roleId="";
		}
		IpRole findByRoleId = iPRoleDao.findByRoleId(roleId);
		/*String coId = ir.getCoId();
		findByRoleId.setCoId(coId);*/
		
		if(findByRoleId==null){	
			userRole.setRoleId(roleId);
			userRole.setCoId(coId);
		}else{
			userRole.setRoleId(findByRoleId.getRoleId());
			userRole.setCoId(coId);
		}
		userRole.setUserId(ipUserEntity.getUserId());
		userRole.setTheId(UUIDTools.uuidRandom());
		userRole.setIsPartTime(flag);
		return userRole;
	}
	
	private IpUser checkIpUser(IpUser ipUserEntity, Map<String, String> resultMap) {
		IpUser ipUser= findUserByUserId(ipUserEntity.getUserId());//按登入号查询user
		/*if(ipUser!=null){
			  getErrorMsg(resultMap,"登录号已存在！");
			  return false;
		}
		return true;*/
		
		return ipUser;
	}
	
	
	private IpUserCompany checkIpUserCompany(IpUserCompany ipUserCompany, Map<String, String> resultMap) {

		IpUserCompany findIpUserCompanyByUserIdAndCoId = ipUserCompanyDao.findIpUserCompanyByUserId(ipUserCompany.getUserId());
		/*if(findIpUserCompanyByUserIdAndCoId!=null){
			  getErrorMsg(resultMap,"已添加该部门！");
			  return false;
		}*/
		
		return findIpUserCompanyByUserIdAndCoId;
		
	}
	
	private IpUserRole checkIpUserRole(IpUserRole ipUserRole, Map<String, String> resultMap) {
		/*if(ipUserRole==null){
			return false;
		}*/
		IpUserRole findIpUserRoleByUserIdAndRoleIdAndIsPartTime = ipUserRoleDao.findIpUserRoleByUserIdAndIsPartTime(ipUserRole.getUserId(),ipUserRole.getIsPartTime());
		/*if(findIpUserRoleByUserIdAndRoleIdAndIsPartTime!=null){
			  getErrorMsg(resultMap,"已添加该职务！");
			  return false;
		}*/
		
		return findIpUserRoleByUserIdAndRoleIdAndIsPartTime;
		
	}
	
	/**
	 * 错误信息 
	 * @param resultMap
	 * @param reason
	 */
	private void getErrorMsg(Map<String, String> resultMap,String reason) {
		resultMap.put("result", "fail");
		resultMap.put("reason", reason);
	}


	public List<IpUser> findUserAll() {
		
		// TODO 自动生成的方法存根
				 return userDao.findUserAll();

	}
	
	public Page<IpUser> getUserAll(Map<String, Object> searchParams,
			PageRequest pageRequest) throws UnsupportedEncodingException {
				
				/* Specification<IpUser> spec = buildSpecification(searchParams);
				 return userDao.findAll(spec, pageRequest);*/
				 
				 //Specification<IpUser> spec = buildSpecification(searchParams);
			      //  return userDao.findAll(spec, pageRequest);
				 //return userDao.findUserAll();
		
		
		    Map<String,String> roleIdAndCoId=getHirerIdAndCoIdBySearchParams(searchParams);
			String hirerId = roleIdAndCoId.get("hirerId");
			String coId = roleIdAndCoId.get("coId");
			String isEnabled = roleIdAndCoId.get("isEnabled");
			
			String loginName = roleIdAndCoId.get("loginName");			
		
		   List initUserByHirerIdAndCoId = iuapUserJdbcDao.getInitUserByHirerIdAndCoId(hirerId, coId,isEnabled,loginName);
		   List<IpUser> buildIpMenuEntityList = buildIpMenuEntityList(initUserByHirerIdAndCoId);
		   // Page<IpUser> pageEntity = ipDataTableService.getPageEntity(pageRequest, buildIpMenuEntityList);
		   return ipDataTableService.getPageEntity(pageRequest, buildIpMenuEntityList);
		   //return buildIpMenuEntityList;
		
	}


	public boolean checkEmployeeNo(String employeeNo) {
		// TODO 自动生成的方法存根
		IpUser ipUser= findUserByEmployeeNo(employeeNo);//按登入号查询user
		if(ipUser!=null){
			  return false;
		}
		return true;
	}


	private IpUser findUserByEmployeeNo(String employeeNo) {
		// TODO 自动生成的方法存根
		return userDao.findIpUserByEmployeeNo(employeeNo);
	}


	public void updateUserByUserId(String userId, String isEnabled) {
		// TODO 自动生成的方法存根
		
		userDao.updateUserByUserId(userId,isEnabled);
		
	}

	@Transactional
	public void saveIpUser(IpUser ipUser) {
		userDao.save(ipUser);
	}


	public IpUser findIpUserByLoginName(String loginName) {
		return userDao.findByLoginName(loginName);
	}	
	
	public List<IpUser> getUserPage(Map<String, Object> searchParams,
			Sort sort) {
		// TODO 自动生成的方法存根
		 Specification<IpUser> spec = buildSpecification(searchParams);
		 return userDao.findAll(spec, sort);
	} 
	
	public List<IpUser> getUserByDeptPage(Map<String, Object> searchParams,
			Sort sort) {
		// TODO 自动生成的方法存根
		 Specification<IpUser> spec = buildSpecification(searchParams);
		 return userDao.findAll(spec, sort);
	} 
	
	/**
     * 创建动态查询条件组合.
     */
    public Specification<IpUser> buildSpecification(Map<String, Object> searchParams) {
        Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
        Specification<IpUser> spec = DynamicSpecifications.bySearchFilter(filters.values(), IpUser.class);
        return spec;
    }
    
    
    private Map<String,String> getHirerIdAndCoIdBySearchParams(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		SearchFilter searchFilterByHirerId =filters.get("EQ_hirerId");
		SearchFilter searchFilterByCoId =filters.get("EQ_coId");
		SearchFilter searchFilterByIsEnabled =filters.get("EQ_isEnabled");
		SearchFilter searchFilterByLoginName =filters.get("LIKE_loginName");
		String hirerId = "";
		String coId = "";
		String isEnabled="";
		String loginName="";
		Map<String,String> dataInfo=new HashMap<String, String>();
		if (searchFilterByHirerId!=null) {
			hirerId = (String) searchFilterByHirerId.value;
		}
		if (searchFilterByCoId!=null) {
			coId = (String) searchFilterByCoId.value;
		}
		
		if (searchFilterByIsEnabled!=null) {
			isEnabled = (String) searchFilterByIsEnabled.value;
		}
		if (searchFilterByLoginName!=null) {
			loginName = (String) searchFilterByLoginName.value;
			try {
				loginName = URLEncoder.encode(loginName,"utf-8");
				loginName=URLDecoder.decode(loginName,"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			
		}
		dataInfo.put("hirerId", hirerId);
		dataInfo.put("coId", coId);
		dataInfo.put("isEnabled", isEnabled);
		dataInfo.put("loginName", loginName);
		return dataInfo;
	}
    
    /**
	 * 通过jdbc查询的结果构建 list<实体>
	 * @param ipRoleMenuList
	 * @return
	 */
	private List<IpUser> buildIpMenuEntityList(List ipUserList) {
		List<IpUser> ipUsers = new ArrayList<IpUser>();
		IpUser ipUser;
		Iterator iterator = ipUserList.iterator();
		 while (iterator.hasNext()) {
			 Map map4ipMenu = (Map) iterator.next();
			 ipUser=new IpUser();
			 CopyPropertiesUtil.copyJdbcProperty(ipUser, map4ipMenu);
			 ipUsers.add(ipUser);
		}
		return ipUsers;
	}


	public IpUser findUserByUserId(String userId) {
		return userDao.findUserByUserId(userId);
	}


//	public Page<IpUser> findUserByUserEmailOrLoginNameOrCellphoneNoLike(
//			Map<String, Object> searchParams, PageRequest pageRequest) throws UnsupportedEncodingException {
//
//		    Map<String,String> userInfomation=getUserBySearchParams(searchParams);
//			String loginName = userInfomation.get("loginName");
//			String isEnabled = userInfomation.get("isEnabled");
//			
//			String loginNameLike=URLEncoder.encode("%"+loginName+"%","utf-8");
//			loginNameLike=URLDecoder.decode(loginNameLike,"utf-8");
//			List<IpUser> userInfoLike = userDao.findUserByUserEmailOrLoginNameOrCellphoneNoLike(loginNameLike,isEnabled);
//		    //List<IpUser> buildIpMenuEntityList = buildIpMenuEntityList(findUserByUserEmailOrLoginNameOrCellphoneNoLike);
//		    return ipDataTableService.getPageEntity(pageRequest, userInfoLike);
//		
//	}
	public Page<IpUser> findUserByUserEmailOrLoginNameOrCellphoneNoLike(
			Map<String, Object> searchParams, PageRequest pageRequest) throws UnsupportedEncodingException {
			Page<IpUser> userInfoLike = getUserAll(searchParams, pageRequest);
		    return userInfoLike;		
	}


	private Map<String, String> getUserBySearchParams(
			Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		SearchFilter searchFilterByLoginName =filters.get("LIKE_loginName");
		SearchFilter searchFilterByIsEnabled =filters.get("EQ_isEnabled");
		String loginName="";
		String isEnabled="";
		Map<String,String> dataInfo=new HashMap<String, String>();
		
		if (searchFilterByLoginName!=null) {
			loginName = (String) searchFilterByLoginName.value;
		}
		
		if (searchFilterByIsEnabled!=null) {
			isEnabled = (String) searchFilterByIsEnabled.value;
		}
		
		dataInfo.put("loginName", loginName);
		dataInfo.put("isEnabled", isEnabled);
		return dataInfo;
	}


	public List<IpUser> findUserByHirerId(String hirerId) {
		return userDao.findUserByHirerId(hirerId);
	}
	
}
